package guru.springframework.controllers;

import static org.mockito.Mockito.RETURNS_DEEP_STUBS;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.HistoryService;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.pvm.process.ProcessDefinitionImpl;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;

import guru.springframework.bean.Result;
import guru.springframework.bean.TaskBean;

/**
 * @Description:请假流程
 * @author hp
 * @date 2018年8月13日 下午5:48:57
 */
@RestController
@RequestMapping("/leaveApply")
public class LeaveApply {
	
	@Autowired  
	private RepositoryService repositoryService; 
	@Autowired  
	private RuntimeService runtimeService;
	
	@Autowired  
	private TaskService taskService; 
	
	@Autowired
	private HistoryService historyService;

	@Autowired
	private IdentityService identityService;
	
	/**
	 * 发布流程
	 * @Description:
	 * @date 2018年8月13日 下午5:59:06
	 */
	@RequestMapping(value="/applyFlow/{titel}/{applyPerson}")
	public Result applyFlow(@PathVariable String titel,@PathVariable String applyPerson){
		
		try {
			
			Deployment deployment = repositoryService.createDeployment().addClasspathResource("processes/leaveDemo.bpmn").name(titel).deploy();
			
			//获取流程定义
			ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).singleResult();
			
			//发布的时候传到申请人，代办人就是申请人。
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("empId", applyPerson);
			
			//绑定用户
			identityService.setAuthenticatedUserId(applyPerson);
			
			//启动流程定义，返回流程实例
			ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId(),variables);
			//设置流程名称
			runtimeService.setProcessInstanceName(processInstance.getId(), titel);
			
			System.out.println("流程id:"+processInstance.getId()+",流程名称:"+deployment.getName());
			
			return Result.success(processInstance.getId());
			
		} catch (Exception e) {
			
			e.printStackTrace();
			return Result.fail(e.getMessage());
		}
	}
	
	/**
	 * 根据指派人查询正在执行的流程信息(可以是员工A，也可以是老板)
	 * @Description:
	 * @date 2018年8月13日 下午5:59:06
	 */
	@RequestMapping(value="/queryFlow/{person}")
	public List<TaskBean> queryFlow(@PathVariable String person){
		List<Task> list = taskService.createTaskQuery().taskAssignee(person).list();
		
		List<TaskBean> taskList = new ArrayList<TaskBean>();
		
		list.forEach(action->{
			TaskBean tb = new TaskBean();
			tb.setAssignee(action.getAssignee());
			tb.setCreateTime(action.getCreateTime());
			
			tb.setTaskId(action.getId());
			tb.setProcessId(action.getProcessInstanceId());
			tb.setStatu("0");
			
			HistoricProcessInstance hp = historyService.createHistoricProcessInstanceQuery().processInstanceId(action.getProcessInstanceId()).singleResult();
			tb.setName(hp.getName());
			
			tb.setApplicant(hp.getStartUserId());
			tb.setRemarks("待审批");
			taskList.add(tb);
		});
		
		return taskList;
	}
	
	
	/**
	 * 流程转到下一级。
	 */
	@RequestMapping(value="/transflow/{taskId}/{bossId}")
	public Result transflow(@PathVariable String taskId,@PathVariable String bossId){
		try {
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("bossId", bossId);
			taskService.complete(taskId, variables);
			return Result.success("");
		} catch (Exception e) {
			e.printStackTrace();
			return Result.fail(e.getMessage());
		}
	}
	
	
	/**
	 * 流程驳回
	 */
	@RequestMapping(value="/rejectFlow/{taskId}")
	public Result rejectFlow(@PathVariable String taskId){
		try {
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("flag", false);
			taskService.complete(taskId, variables);
		return Result.success("");
		} catch (Exception e) {
			e.printStackTrace();
			return Result.fail(e.getMessage());
		}
	}
	
	
	
	/**
	 * 流程通过
	 */
	@RequestMapping(value="/passFlow/{taskId}")
	public Result passFlow(@PathVariable String taskId){
		try {
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("flag", true);
			taskService.complete(taskId, variables);	
		return Result.success("");
		} catch (Exception e) {
			e.printStackTrace();
			return Result.fail(e.getMessage());
		}
	}
	
	
	
	
	
	
	
	/**
	 * 完成流程任务
	 */
	@RequestMapping(value="/flowReceipt/{taskId}")
	public Result flowReceipt(@PathVariable String taskId){
		try {
			taskService.complete(taskId);
			return Result.success("");
		} catch (Exception e) {
			e.printStackTrace();
			return Result.fail(e.getMessage());
		}
	}
	
	
	/**
	 * @Description:根据申请人查询任务信息，已开始或者已结束的任务。
	 * @date 2018年8月15日 下午3:36:44
	 */
	@RequestMapping(value="/queryHisTask/{person}/{type}")
	public List<TaskBean> queryHisTask(@PathVariable String person,@PathVariable String type){
		
		List<TaskBean> list = new ArrayList<TaskBean>();
		
		List<HistoricProcessInstance> hpList = new ArrayList<HistoricProcessInstance>();
		
		if("unFinished".equals(type)){
			//获取流程发起人正在运行的流程
			hpList = historyService.createHistoricProcessInstanceQuery().startedBy(person).unfinished().list();
			
			System.out.println("HistoricProcessInstance : "+JSONArray.toJSONString(hpList));
			
			for(HistoricProcessInstance action : hpList){
				TaskBean tb = new TaskBean();
				String processDefinitionId = action.getId();
				System.out.println("processDefinitionId : "+processDefinitionId);
				List<Task> taskList = taskService.createTaskQuery().processInstanceId(processDefinitionId)
						.orderByTaskCreateTime().desc().list();
				
				Task tk = taskList.get(0);
				tb.setApplicant(person);
				tb.setCreateTime(action.getStartTime());
				tb.setName(action.getName());
				tb.setTaskId(tk.getId());
				tb.setStatu("0");
				tb.setRemarks("待受理");
				tb.setProcessId(action.getId());
				if(!tk.getAssignee().equals(person)){
					tb.setAssignee(tk.getAssignee());
					tb.setRemarks("已受理");
				}
				list.add(tb);
			}
			
			
		}else{
			//获取流程发起人已完成的流程
			hpList = historyService.createHistoricProcessInstanceQuery().startedBy(person).finished().list();
			
			for(HistoricProcessInstance action : hpList){
				TaskBean tb = new TaskBean();
				String processDefinitionId = action.getId();
				System.out.println("processDefinitionId : "+processDefinitionId);
				List<HistoricTaskInstance> taskList = historyService.createHistoricTaskInstanceQuery().processInstanceId(processDefinitionId)
									.orderByHistoricTaskInstanceEndTime().desc().list();
				HistoricTaskInstance tk = taskList.get(0);
				tb.setApplicant(person);
				tb.setCreateTime(action.getStartTime());
				tb.setName(action.getName());
				tb.setTaskId(tk.getId());
				tb.setStatu("1");
				tb.setRemarks("已办结");
				tb.setProcessId(action.getId());
				tb.setEndTime(action.getEndTime());
				tb.setAssignee(tk.getAssignee());
				list.add(tb);
			}
			
		}
		
		System.out.println("taskBeanList"+JSONArray.toJSONString(list));
		
		return list;
	}
	
	
	
}
